//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "RestaurantDetailViewController.h"
#import "BookViewController.h"
#import "CommentCell.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "config.h"
@interface RestaurantDetailViewController (){
}

@end

@implementation RestaurantDetailViewController
@synthesize btnRestaurant;
@synthesize btnRemark;
@synthesize btnMap;
@synthesize svMain;
@synthesize sliderLabel;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [self addBasicView];
    [self initScrollView];
    [self getMerchant:_merchantId];
}

- (void)viewDidUnload
{
    [self setBtnRestaurant:nil];
    [self setBtnRemark:nil];
    [self setBtnMap:nil];
    [self setSvMain:nil];
    [self setSliderLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title=@"我的惠宝";
    }
    return self;
}
- (void) getMerchant:(int) merchantId
{
    //异步请求
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?merchantID=%d",url_detail,merchantId]] ;
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate: self];
    [request startAsynchronous];
    
    

    
}
//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)requestFinished:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *jsonStr = [request responseString];
    //NSLog(@"%@",jsonStr);
    NSDictionary *dic = [[jsonStr JSONValue] valueForKey:@"data"];
    if((NSNull *)dic != [NSNull null]){
        //详情页面
        view1.lbName.text= [dic valueForKey:@"NAME"];
        view1.lbCuisine.text= [NSString stringWithFormat:@"菜系：%@",[dic valueForKey:@"CUISINE_NAME"] ];
        view1.lbAddress.text= [dic valueForKey:@"ADDRESS"];
        view1.lbDiscount.text= [[dic valueForKey:@"DISCOUNT"] stringValue];
        view1.lbTransport.text= [NSString stringWithFormat:@"公交线路：%@",[dic valueForKey:@"BUS_ROUTE"]];
        view1.lbDrive.text= [NSString stringWithFormat:@"自驾线路：%@",[dic valueForKey:@"DRIVE_ROUTE"]];
        view1.lbMemo.text= [dic valueForKey:@"MEMO"];
        view1.score =  [dic valueForKey:@"AVG_SCORE"] == [NSNull null]? [NSNumber numberWithFloat:0] : [NSNumber numberWithFloat:[[dic valueForKey:@"AVG_SCORE"] floatValue]];

        [view1.lbTransport sizeToFit];
        [view1.lbTransport sizeToFit];
        [view1.lbMemo sizeToFit];
        [self setImageView:[[dic valueForKey:@"MERCHANT_ID"] intValue] withURL:[dic valueForKey:@"IMAGEPATH"]];
        //地图页面
        if([dic valueForKey:@"AVG_SCORE"] != [NSNull null]){
            NSURL *url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@%f,%f",url_googlemap, [[dic valueForKey:@"LATITUDE"] floatValue], [[dic valueForKey:@"LONGTITUDE"] floatValue] ]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            [view3.webView loadRequest:[ NSURLRequest requestWithURL: url ]];
        }
        //评论页面
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?merchantId=%d",url_commentList,_merchantId]] ;
        request = [ASIHTTPRequest requestWithURL:url];
        [request startSynchronous];
        
        NSString *jsonStr = [request responseString];
        
        NSDictionary *dic = [jsonStr JSONValue];
        tableDataArray = [dic valueForKey:@"data"];
        [view2.tbComment reloadData];
//        NSLog(@"%@",tableDataArray);
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
}
- (void)setImageView:(int) id withURL:(NSString *) imagePath{
    NSString *imageStr = [NSString stringWithFormat:@"%@?inputPath=%@",url_image,imagePath];
    //        NSLog(@"%@",imageStr);
    NSString *imageName = [NSString stringWithFormat:@"%d%@",id,@".temp"];
    //        NSLog(@"%@",imageName);
    if(imageName){
        NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
        
        if (![[NSFileManager defaultManager] fileExistsAtPath:imageDataPath]) {
            
            NSURL *imageUrl = [NSURL URLWithString:[imageStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
            [imageData writeToFile:imageDataPath atomically:YES];
            UIImage *image = [UIImage imageWithData:imageData];
            [view1.imageView setImage:image];
        }else{
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
            if (image) {
                [view1.imageView setImage:image];
            }
            else
            {
                image = [UIImage imageNamed:@"Placeholder.png"];
                //placeholder为在未加载完成加载图片时显示的默认图片
                [view1.imageView setImage:image];
            }
            
        }
    }

}

- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void) addBasicView
{
    btnRestaurant.showsTouchWhenHighlighted = YES;  //指定按钮被按下时发光
    [btnRestaurant setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//此时选中
    [btnRestaurant addTarget:self action:@selector(btnRestaurantAction) forControlEvents:UIControlEventTouchUpInside];
    btnRemark.showsTouchWhenHighlighted = YES;  //指定按钮被按下时发光
    [btnRemark setTitleColor:[UIColor colorWithRed:(220/255.0) green:(220/255.0) blue:(220/255.0) alpha:1] forState:UIControlStateNormal];//此时未被选中
    [btnRemark addTarget:self action:@selector(btnRemarkAction) forControlEvents:UIControlEventTouchUpInside];
    
    btnMap.showsTouchWhenHighlighted = YES;  //指定按钮被按下时发光
    [btnMap setTitleColor:[UIColor colorWithRed:(220/255.0) green:(220/255.0) blue:(220/255.0) alpha:1] forState:UIControlStateNormal];//此时未被选中
    [btnMap addTarget:self action:@selector(btnMapAction) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark-
#pragma mark 界面按钮事件

- (void) btnActionShow
{
    if (currentPage == 0) {
        [self btnRestaurantAction];
    }
    else if (currentPage == 1) {
        [self btnRemarkAction];
    }
    else if (currentPage == 2) {
        [self btnMapAction];
    }
}

- (void) btnRestaurantAction
{
    [btnRestaurant setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//此时选中
    [btnRemark setTitleColor:[UIColor colorWithRed:(220/255.0) green:(220/255.0) blue:(220/255.0) alpha:1] forState:UIControlStateNormal];//此时未被选中
    [btnMap setTitleColor:[UIColor colorWithRed:(220/255.0) green:(220/255.0) blue:(220/255.0) alpha:1] forState:UIControlStateNormal];//此时未被选中
    UIImage *im = [UIImage imageNamed:@"ic_detail_comment"];
    [btnRemark setImage:im forState:UIControlStateNormal];
    im = [UIImage imageNamed:@"ic_detail_base_selected"];
    [btnRestaurant setImage:im forState:UIControlStateNormal];
    im = [UIImage imageNamed:@"ic_detail_transport"];
    [btnMap setImage:im forState:UIControlStateNormal];

    [RestaurantView beginAnimations:nil context:nil];//动画开始
    [RestaurantView setAnimationDuration:0.3];
    
    sliderLabel.frame = CGRectMake(1, 74, 120, 2);
    [svMain setContentOffset:CGPointMake(320*0, 0)];//页面滑动
    
    [RestaurantView commitAnimations];
}

- (void) btnRemarkAction
{
    [btnRemark setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//此时选中
    [btnRestaurant setTitleColor:[UIColor colorWithRed:(220/255.0) green:(220/255.0) blue:(220/255.0) alpha:1] forState:UIControlStateNormal];//此时未被选中
    [btnMap setTitleColor:[UIColor colorWithRed:(220/255.0) green:(220/255.0) blue:(220/255.0) alpha:1] forState:UIControlStateNormal];//此时未被选中

    UIImage *im = [UIImage imageNamed:@"ic_detail_comment_selected"];
    [btnRemark setImage:im forState:UIControlStateNormal];
    im = [UIImage imageNamed:@"ic_detail_base"];
    [btnRestaurant setImage:im forState:UIControlStateNormal];
    im = [UIImage imageNamed:@"ic_detail_transport"];
    [btnMap setImage:im forState:UIControlStateNormal];

    [CommentView beginAnimations:nil context:nil];//动画开始
    [CommentView setAnimationDuration:0.3];
    
    sliderLabel.frame = CGRectMake(106, 74, 120, 2);
    [svMain setContentOffset:CGPointMake(320*1, 0)];
    
    [CommentView commitAnimations];
}
- (void) btnMapAction
{
    [btnMap setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//此时选中
    [btnRemark setTitleColor:[UIColor colorWithRed:(220/255.0) green:(220/255.0) blue:(220/255.0) alpha:1] forState:UIControlStateNormal];//此时未被选中
    [btnRestaurant setTitleColor:[UIColor colorWithRed:(220/255.0) green:(220/255.0) blue:(220/255.0) alpha:1] forState:UIControlStateNormal];//此时未被选中
    UIImage *im = [UIImage imageNamed:@"ic_detail_comment"];
    [btnRemark setImage:im forState:UIControlStateNormal];
    im = [UIImage imageNamed:@"ic_detail_base"];
    [btnRestaurant setImage:im forState:UIControlStateNormal];
    im = [UIImage imageNamed:@"ic_detail_transport_selected"];
    [btnMap setImage:im forState:UIControlStateNormal];

    [MapView beginAnimations:nil context:nil];//动画开始
    [MapView setAnimationDuration:0.3];
    
    sliderLabel.frame = CGRectMake(212, 74, 120, 2);
    [svMain setContentOffset:CGPointMake(320*2, 0)];
    
    [MapView commitAnimations];
}

- (IBAction)doShareSMS:(id)sender {
    NSURL *url = [NSURL URLWithString:url_shareSMS];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue:[NSString stringWithFormat:@"%d",_merchantId] forKey:@"merchantID"];
   
    [request startSynchronous];
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
//    NSLog(@"%@",dic);
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
    {
//        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
//                                                      message:[dic valueForKey:@"data"]
//                                                     delegate:nil
//                                            cancelButtonTitle:@"确定"
//                                            otherButtonTitles:nil];
//        [alert show];
//        [alert release];
       [self sendSMS:[dic valueForKey:@"data"] recipientList:nil];


    }

}
//调用sendSMS函数
//内容，收件人列表
- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    
    if([MFMessageComposeViewController canSendText])
        
    {
        
        controller.body = bodyOfMessage;
        
//        controller.recipients = recipients;
        
        controller.messageComposeDelegate = self;
//        [self.navigationController pushViewController:controller animated:YES];
        [self presentModalViewController:controller animated:YES];
        [controller release];
    }
    
}

// 处理发送完的响应结果
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissModalViewControllerAnimated:YES];
    
    if (result == MessageComposeResultCancelled)
        NSLog(@"Message cancelled");
    else if (result == MessageComposeResultSent)
        NSLog(@"Message sent") ;
    else 
        NSLog(@"Message failed") ;
}
    
- (IBAction)doAddFavorite:(id)sender {
    NSURL *url = [NSURL URLWithString:url_addFavorite];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    int memberId = [[Config Instance] getMemberId];
    [request setPostValue:[NSString stringWithFormat:@"%d",memberId] forKey:@"memberID"];
    [request setPostValue:[[Config Instance] getPassword] forKey:@"password"];
    [request setPostValue:[NSString stringWithFormat:@"%d",_merchantId] forKey:@"merchantID"];
    
    [request startSynchronous];
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    //    NSLog(@"%@",dic);
//    NSString *msg = @"";
//    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
//    {
//        msg = [dic valueForKey:@"log"];
//    }
//    else
//    {
//        msg = [dic valueForKey:@"log"];
//    }
    UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                 message:[dic valueForKey:@"log"]
                                        delegate:nil
                                        cancelButtonTitle:@"确定"
                                       otherButtonTitles:nil];
    [alert show];
    [alert release];

}

#pragma mark 左右滑动相关函数

- (void)initScrollView {
    
    //设置 tableScrollView
    // a page is the width of the scroll view
    svMain.pagingEnabled = YES;
    svMain.clipsToBounds = NO;
    svMain.contentSize = CGSizeMake(svMain.frame.size.width * 3, svMain.frame.size.height*2);
    svMain.showsHorizontalScrollIndicator = NO;
//    svMain.showsVerticalScrollIndicator = NO;
//    svMain.scrollsToTop = NO;
    svMain.delegate = self;
    
    [svMain setContentOffset:CGPointMake(0, 0)];
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"img_bg_background.png"]];
    svMain.backgroundColor = background; [background release];

    //公用
    currentPage = 0;
    pageControl.numberOfPages = 3;
    pageControl.currentPage = 0;
    pageControl.backgroundColor = [UIColor whiteColor];
    [self createAllEmptyPagesForScrollView];
}

- (void)createAllEmptyPagesForScrollView {
    
    NSArray *arr = [[NSBundle mainBundle] loadNibNamed:@"RestaurantView" owner:nil options:nil];
    view1 = (RestaurantView *)[[arr objectAtIndex:0] retain];
    view1.frame = CGRectMake(320*0, 0, 320, svMain.frame.size.height);
    view1.lbName.text=@"";
    [view1.btnBook addTarget:self action:@selector(doBookAction) forControlEvents:UIControlEventTouchUpInside];
    [view1.btnPhone addTarget:self action:@selector(doPhoneAction) forControlEvents:UIControlEventTouchUpInside];

    [svMain addSubview: view1];
    
    arr = [[NSBundle mainBundle] loadNibNamed:@"CommentView" owner:nil options:nil];
    view2 = (CommentView *)[[arr objectAtIndex:0] retain];
    view2.frame = CGRectMake(320*1, 0, 320, svMain.frame.size.height);
    view2.tbComment.delegate = self;
    view2.tbComment.dataSource = self;
    [svMain addSubview: view2];
    
//    CGRect webFrame = CGRectMake(320*2,0.0,320.0,svMain.frame.size.height);
    //webFrame.origin.y+=25;
    arr = [[NSBundle mainBundle] loadNibNamed:@"MapView" owner:nil options:nil];
    view3 = (MapView *)[[arr objectAtIndex:0] retain];
    view3.frame = CGRectMake(320*2, 0, 320, svMain.frame.size.height);
//    view3 = [[UIWebView alloc] initWithFrame:webFrame];
//    [view3 setBackgroundColor:[UIColor whiteColor]];//设置北京为白色
//    view3.scalesPageToFit = YES;//适应屏幕大小
    
    [svMain addSubview: view3]; 
    
}

// 评论列表设置
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"CommentCellIdentifier";
    
    CommentCell *cell = (CommentCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //        if (cell == nil) {
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CommentCell" owner:nil options:nil];
    cell = [array objectAtIndex:0];
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    //        }
    
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    NSString *name = @"";
    if([item valueForKey:@"NICKNAME"] == [NSNull null])
        name = [item valueForKey:@"MOBILE"];
    else
        name = [item valueForKey:@"NICKNAME"];
    cell.lbNickName.text = name;
    cell.lbScore1.text = [NSString stringWithFormat:@"%@分",[item valueForKey:@"环境"]];
    cell.lbScore2.text = [NSString stringWithFormat:@"%@分",[item valueForKey:@"交通"]];
    cell.lbScore3.text =  [NSString stringWithFormat:@"%@分",[item valueForKey:@"菜肴"]];
    cell.score = [item valueForKey:@"AGREE"] == [NSNull null]? [NSNumber numberWithFloat:0] : [NSNumber numberWithFloat:[[item valueForKey:@"AGREE"] floatValue]];
    cell.lbContent.text = [item valueForKey:@"CONTENT"];

    return cell;
        
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
        //传递商户id参数
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"点评内容"
                                    message:[item objectForKey:@"CONTENT"]
                                    delegate:nil
                                    cancelButtonTitle:@"确定"
                                    otherButtonTitles:nil];
    [alert show];
    [alert release];

    
    //其他cell的事件
    
}


-(void) doBookAction{
    BookViewController  *view = [[BookViewController alloc] initWithNibName:@"BookViewController" bundle:nil];
    //传递商户id参数
    view.merchantId = _merchantId;
    view.merchantName = view1.lbName.text;
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
    //        [view release];

}
-(void) doPhoneAction{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://4000509177"]];
    NSLog(@"%@",@"4000509177");
    
}
// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    CGFloat pageWidth = self.svMain.frame.size.width;
    int page = floor((self.svMain.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    
    pageControl.currentPage = page;
    currentPage = page;
    pageControlUsed = NO;
    [self btnActionShow];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //暂不处理 - 其实左右滑动还有包含开始等等操作，这里不做介绍
}

- (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view
{
    return YES;
}
- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
    return NO;
}


- (void)dealloc {
    [btnRestaurant release];
    [btnRemark release];
    [btnMap release];
    [svMain release];
    [sliderLabel release];
    [super dealloc];
}
@end
